package com.doit.demo02;

import java.util.Arrays;
import java.util.Iterator;

public class MyArrayList<E> implements Iterable<E>{
    private int size;
    private Object[]arr;
    private Object[]empty={};

    public MyArrayList(){arr=empty;}
    public boolean add(E e)
    {
        //如果集合的个数 与数组长度相同 扩容
        if(size==arr.length)
        {
            grow();
        }
        arr[size]=e;
        size++;
        return true;
    }
    public void grow()
    {
        //如果长度为0 说明是第一次 直接一个长度为10的数组
        if(arr.length==0)
        {
            arr=new Object[10];
            return;
        }
        int old = arr.length;
        int newCapacity = old+(old>>1);//长度变为原来的1.5倍
        arr = Arrays.copyOf(arr,newCapacity);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            if(i==size+1)
                sb.append(arr[i]);
            else
                sb.append(arr[i]).append(",");
        }
        return sb.toString();
    }

    public E remove(int index)
    {
        checkIndex(index);
        E old = (E) arr[index];//记录被删除的数据
        int move =size-index-1;
        System.arraycopy(arr,index,arr,index-1,move);
        arr[--size]=null;
        return old;
    }
    public void checkIndex(int index)
    {
        if(index<0 || index >=size)
            throw new ArrayIndexOutOfBoundsException(index);
    }

    public void add(int index,E e)
    {
        checkIndex(index);
        //检查是否需要扩容
        if(size==arr.length)
            grow();
        int move = size-index;
        System.arraycopy(arr,index,arr,index+1,move);
        arr[index]=e;
        size++;
    }

    //指定索引处修改元素
    public E set (int index,E e)
    {
        checkIndex(index);
        E old = (E) arr[index];
        arr[index]=e;
        return old;
    }
    public int size(){return size;}
    public E get(int index)
    {
        checkIndex(index);
        return (E) arr[index];
    }
    public Iterator<E> iterator(){return new itr<E>();}
    public class itr<E>implements Iterator<E>{
        public int cur = 0;
        @Override
        public boolean hasNext() {
            return cur!=size;
        }

        @Override
        public E next() {
            int i = cur;
            Object[]a=MyArrayList.this.arr;
            cur++;
            return (E) a[i];
        }
    }
//    @Override
//    public Iterator<E> iterator() {return new Itr<E>();}
//    private class Itr <E> implements Iterator<E>{
//
//        private int cursor =0;
//        @Override
//        public boolean hasNext() {
//            return cursor!=size;
//        }
//        @Override
//        public E next() {
//            int i =cursor;
//            Object[]arr=MyArrayList.this.arr;
//            cursor++;
//            return (E) arr[i];
//        }
//    }
}
